package com.deer.wms.inventory.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deer.wms.base.system.model.Cell.CellInfoDto;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.constant.InventoryConstant;
import com.deer.wms.inventory.dao.StockTakeMasterMapper;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.stockTake.*;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.StockTakeDetailService;
import com.deer.wms.inventory.service.StockTakeMasterService;
import com.deer.wms.inventory.service.StockTakeTaskService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.service.ValidatorService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.deer.wms.project.root.util.DateUtils.getNowDateTimeString;
import static com.deer.wms.project.root.util.FunctionUtil.nvl;

/**
 * Created by 郭靖勋 on 2020/02/06.
 */
@Service
@Transactional
public class StockTakeMasterServiceImpl extends SuperServiceImpl<StockTakeMasterMapper,StockTakeMaster> implements StockTakeMasterService {

    @Autowired
    private StockTakeMasterMapper stockTakeMasterMapper;
    @Autowired
    private ValidatorService validatorService;
    @Autowired
    private StockTakeMasterService stockTakeMasterService;
    @Autowired
    private StockTakeTaskService stockTakeTaskService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private ItemInfoService itemInfoService;
    @Autowired
    private CaseMasterService caseMasterService;
    @Autowired
    private StockTakeDetailService stockTakeDetailService;

    @Override
    public List<StockTakeMaster> findList(StockTakeMasterCriteria criteria) {
        return stockTakeMasterMapper.findList(criteria);
    }

    /**
     * 新建盘点任务，并生成盘点下架任务
     * @param stockTakeData
     * @param currentUser
     */
    @Override
    public void createStockTakeMaster(StockTakeData stockTakeData, CurrentUser currentUser) {
        //状态    2-等待审核(初始化)  1-审核通过  0-审核中  -1-审核退回
        Integer caseState = 2;

        String tableName = "stock_take_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo = "PD" + "-" + nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();

        StockTakeMaster stockTakeMaster = stockTakeData.getStockTakeMaster();
        //审核
        caseState = caseMasterService.createCase(billNo, 5, currentUser.getUserId(), stockTakeMaster.getWareId(), stockTakeMaster.getOrganizationId());

        if (StringUtils.isNotBlank(stockTakeMaster.getItemCode())) {
            ItemInfo itemInfo = itemInfoService.findByCode(stockTakeMaster.getItemCode()).get(0);
            if (itemInfo != null) {
                stockTakeMaster.setItemName(itemInfo.getItemName());
            }
        }
        stockTakeMaster.setCreateUserId(createUserId);
        stockTakeMaster.setCreateUserName(createUserName);
        stockTakeMaster.setBillNo(billNo);
        stockTakeMaster.setCaseState(caseState);
        stockTakeMasterService.save(stockTakeMaster);

        List<StockTakeDetail> stockTakeDetails = new ArrayList<>();

        for (ItemInfo itemInfo : stockTakeData.getItems()) {
            StockTakeDetail stockTakeDetail = new StockTakeDetail();
            stockTakeDetail.setStockTaskMasterId(stockTakeMaster.getStockTakeMasterId());
            stockTakeDetail.setItemInfoId(itemInfo.getId());
            stockTakeDetail.setItemCode(itemInfo.getItemCode());
            stockTakeDetail.setItemName(itemInfo.getItemName());
            stockTakeDetails.add(stockTakeDetail);
        }
        stockTakeDetailService.saveBatch(stockTakeDetails);
        if (caseState == 1) {
            this.saveStockTakeTasks(stockTakeMaster, stockTakeDetails, billNo, createUserId, createUserName, createTime);
        }
    }

    public void saveStockTakeTasks(StockTakeMaster stockTakeMaster, List<StockTakeDetail> stockTakeDetails, String billNo, Integer createUserId,
                                   String createUserName, String createTime) {
//        //审核后生成盘点任务
//        //Step1.找到对应的库存
//        StockTakeMasterDto stockTakeMasterDto = new StockTakeMasterDto();
//        stockTakeMasterDto.setWareId(stockTakeMaster.getWareId());
//        stockTakeMasterDto.setOrganizationId(stockTakeMaster.getOrganizationId());
//        //处理抽盘逻辑  随机从List中找出几个
//        if (stockTakeMaster.getIfRandom() == 1) {
//            //抽盘
//            List<StockTakeDetail> randomList = RandomUtil.getRandomList(stockTakeDetails, stockTakeMaster.getRandomNum());
//            stockTakeMasterDto.setStockTakeDetails(randomList);
//        }else {
//            stockTakeMasterDto.setStockTakeDetails(stockTakeDetails);
//        }
//        List<Inventory> list = inventoryService.getInventoryByFromInfo(stockTakeMasterDto);
//
//        //Step2.根据已有的库存生成盘点任务
//        for (int i = 0; i < list.size(); i++) {
//            StockTakeTask stockTakeTask = new StockTakeTask();
//            stockTakeTask.setStockTakeMasterId(stockTakeMaster.getStockTakeMasterId());
//            stockTakeTask.setCreateTime(createTime);
//            stockTakeTask.setTaskUserId(createUserId);
//            stockTakeTask.setTaskUserName(createUserName);
//            stockTakeTask.setBillNo(billNo);
//            //库存id
//            stockTakeTask.setInventoryId(list.get(i).getInventoryId());
////            stockTakeTask.setTaskQuantity(list.get(i).getQuantity());
//            //库存数量  需要判断盘点方式是明盘还是盲盘
//            if (stockTakeMaster.getOpType() == 1) {
//                //明盘
//                stockTakeTask.setType(InventoryConstant.INV_CHECK_TASK_TYPE_11);
//            } else {
//                stockTakeTask.setType(InventoryConstant.INV_CHECK_TASK_TYPE_12);
//            }
//            stockTakeTask.setState(InventoryConstant.INV_CHECK_TASK_STATE_UNDO);
//            stockTakeTaskService.save(stockTakeTask);
//        }
//        stockTakeMaster.setDynamicFromTime(DateUtil.now());
//        stockTakeMasterService.updateById(stockTakeMaster);
//        this.updateStockTakeMasterState(stockTakeMaster.getStockTakeMasterId());
    }

    private void saveTakeTask(List<Map<String,Object>> cellList,String billNo,Integer stockTakeMasterId){
        System.out.println("cellList------------:"+cellList);
        if (cellList.size()>0){
            int i = 1;
            for (Map<String,Object> cell : cellList){
                StockTakeTask task = new StockTakeTask();
                task.setTaskBillNo(billNo +"-"+ i);
                i++;
                task.setStockTakeMasterId(stockTakeMasterId);
                task.setBoxCode(String.valueOf(cell.get("boxCode")));
                task.setCellCode(String.valueOf(cell.get("cellCode")));
                Integer inventoryId = Integer.valueOf(String.valueOf(cell.get("inventoryId")));
                task.setInventoryId(inventoryId);
                task.setCreateTime(getNowDateTimeString());
                task.setType(11);
                task.setState(1);
                stockTakeTaskService.save(task);
            }
        }else {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"数据错误");
        }
    }

    @Override
    public void saveStockTakeTasks(StockTakeMaster stockTakeMaster, String billNo, Integer createUserId, String createUserName, String createTime) {
        // 审核后生成盘点任务
        List<Inventory> list = inventoryService.getInventoryByFromInfo(stockTakeMaster);

        for(int i=0;i<list.size();i++){
            StockTakeTask stockTakeTask = new StockTakeTask();
            stockTakeTask.setStockTakeMasterId(stockTakeMaster.getStockTakeMasterId());
            stockTakeTask.setCreateTime(createTime);
            stockTakeTask.setTaskUserId(createUserId);
            stockTakeTask.setTaskUserName(createUserName);
            stockTakeTask.setTaskBillNo(billNo);
            stockTakeTask.setInventoryId(list.get(i).getInventoryId());
//                stockTakeTask.setTaskQuantity(list.get(i).getQuantity());
            stockTakeTask.setType(11);
            stockTakeTask.setState(1);
            stockTakeTaskService.save(stockTakeTask);
        }
    }

    @Override
    public void updateStockTakeMasterState(Integer stockTakeMasterId){
        List<StockTakeTaskDto> stockTakeTaskDtos = stockTakeTaskService.findList(new StockTakeTaskCriteria(stockTakeMasterId));
        int check = 0;
        int quantity = 0;
        if(stockTakeTaskDtos.size()>0){
            for(StockTakeTaskDto stockTakeTaskDto : stockTakeTaskDtos){
                //如果有未完成的就累加1
                if(stockTakeTaskDto.getState().equals(1)){
                    check++;
                }
                //如果复盘完成同时差异数量不为0的话累加1
                if(!Objects.equals(nvl(stockTakeTaskDto.getDifferQuantity()), 0.0d)
                        && stockTakeTaskDto.getState().equals(2)
                        && (stockTakeTaskDto.getType().equals(21) ||stockTakeTaskDto.getType().equals(22))){
                    quantity++;
                }
            }
            StockTakeMaster stockTakeMaster = getById(stockTakeMasterId);
            if(check>0){
                //有未完成的任务设置状态为盘点中
                stockTakeMaster.setState(3);
            }else{
                //如果复盘后累加数量还是有差异状态改为盘点完成(需调整)
                if(quantity>0){
                    stockTakeMaster.setState(5);
                }
                //复盘后累加数量小于等于0说明数量无差异状态改为盘点完成(无差异)
                else{
                    stockTakeMaster.setState(4);
                }
            }
            updateById(stockTakeMaster);
        }
    }

    @Override
    public StockTakeMaster findBy(String field, String value) {
        QueryWrapper<StockTakeMaster> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }
}
